const fs = require('fs')
const path = require('path')

const file1 = path.resolve(__dirname, './text.json')
const file2 = path.resolve(__dirname, './text2.json')

const readFilePromise = (filename) => {
  if(!filename) {
    console.log('文件名不能为空!')
    return
  }
  return new Promise((resolve, reject) => {
    fs.readFile(filename, (err, data) => {
      if (err) {
        reject(err)
      } else {
        setTimeout(() => {
          resolve(data.toString())
        }, 500)
      }
    })
  })
}

// readFilePromise(file1).then(res => {
//   let f1 = JSON.parse(res)
//   console.log(f1)
//   return readFilePromise(file2)
// }).then(res => {
//   let f2 = JSON.parse(res)
//   console.log(f2)
// })

const readFileAsync = async () => {
  console.log('start');
  const f1 = await readFilePromise(file1)
  const f2 = await readFilePromise(file2)

  console.log('await------------------------')
  console.log(JSON.parse(f1))
  console.log(f2)
  console.log('await------------------------')
}

readFileAsync()

// promise.all()
// Promise.all([readFilePromise(file1), readFilePromise(file2)]).then(datas => {
//   console.log('------promise.all()------')+
//   console.log(datas instanceof Array)
//   console.log(datas[0])
//   console.log(datas[1])
// })

// promise.race()
// Promise.race([readFilePromise(file1), readFilePromise(file2)]).then(data => {
//   console.log('------promise.race()------') 
//   console.log(data instanceof Array)
//   console.log(data)
// })